<template>
  <view class="music-player-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="nav-left" @click="goBack">
          <u-icon name="arrow-left" size="20" color="#fff"></u-icon>
        </view>
        <view class="nav-title">{{ currentSound.name }}</view>
        <view class="nav-right" @click="showActionSheet">
          <u-icon name="more-dot-fill" size="20" color="#fff"></u-icon>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 旋转的音乐标志 -->
      <view class="music-disc-container">
        <view class="disc-wrapper" :class="{ 'rotating': isPlaying }">
          <view class="music-disc">
            <view class="disc-center">
              <image
                  style="border-radius: 50rpx"
                  src="http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/fc1d61d4-16ad-4489-97e0-31e3fd16fff9.jpg?Expires=4911628274&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=DIEiLHKgHSs4F0OUWE2fDZRwOpk%3D"
                  mode="aspectFit"
              ></image>
             </view>
            <!-- 旋转的装饰环 -->
            <view class="disc-ring ring-1"></view>
            <view class="disc-ring ring-2"></view>
            <view class="disc-ring ring-3"></view>
          </view>
        </view>
      </view>

      <!-- 音乐信息 -->
      <view class="music-info">
        <view class="sound-name">{{ currentSound.name }}</view>
        <view class="sound-desc">{{ currentSound.description }}</view>
      </view>

      <!-- 播放控制区域 -->
      <view class="player-controls">
        <!-- 进度条 -->
        <view class="progress-section">
          <text class="time-text">{{ formatTime(currentTime) }}</text>
          <slider 
            class="progress-slider" 
            :value="progressPercent"
            @change="seekTo"
            activeColor="#25772f"
            backgroundColor="rgba(255,255,255,0.3)"
            block-size="12"
          />
          <text class="time-text">{{ formatTime(duration) }}</text>
        </view>

        <!-- 控制按钮 -->
        <view class="control-buttons">
          <view class="control-btn" @click="toggleLoop">
            <u-icon 
              :name="isLoop ? 'reload' : 'more-circle'" 
              size="20" 
              :color="isLoop ? '#25772f' : '#fff'"
            ></u-icon>
          </view>
          <view class="control-btn" @click="previousSound">
            <!-- #ifdef MP-WEIXIN -->
            <text class="control-text">⏮</text>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
            <u-icon name="arrow-left" size="24" color="#fff"></u-icon>
            <!-- #endif -->
          </view>
          <view class="control-btn main-play-btn" @click="togglePlay">
            <u-icon 
              :name="isPlaying ? 'pause' : 'play-right'" 
              size="28" 
              color="#25772f"
            ></u-icon>
          </view>
          <view class="control-btn" @click="nextSound">
            <!-- #ifdef MP-WEIXIN -->
            <text class="control-text">⏭</text>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
            <u-icon name="arrow-right" size="24" color="#fff"></u-icon>
            <!-- #endif -->
          </view>
          <view class="control-btn" @click="toggleFavorite">
            <u-icon 
              :name="isFavorite ? 'heart-fill' : 'heart'" 
              size="20" 
              :color="isFavorite ? '#ff4757' : '#fff'"
            ></u-icon>
          </view>
        </view>

        <!-- 音量控制 -->
        <view class="volume-section">
          <!-- #ifdef MP-WEIXIN -->
          <text class="volume-icon">-</text>
          <view class="volume-tip">
            <text class="volume-tip-text">请使用手机音量键调节</text>
          </view>
          <text class="volume-icon">+</text>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <text class="volume-icon">-</text>
          <slider 
            class="volume-slider" 
            :value="volume" 
            @change="changeVolume"
            activeColor="#25772f"
            backgroundColor="rgba(255,255,255,0.3)"
            block-size="10"
          />
          <text class="volume-icon">+</text>
          <!-- #endif -->
        </view>
      </view>

      <!-- 左下角词条名称 -->
      <view class="sound-tag">
        <text class="tag-text">{{ currentSound.name }}</text>
      </view>
    </view>

    <!-- 操作菜单 -->
    <u-action-sheet 
      :list="actionList" 
      v-model="showAction" 
      @click="handleAction"
      border-radius="20"
    ></u-action-sheet>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      currentSound: {},
      soundList: [],
      currentIndex: 0,
      isPlaying: false,
      isLoop: true,
      isFavorite: false,
      volume: 50,
      currentTime: 0,
      duration: 0,
      audioContext: null,
      backgroundAudioManager: null, // 微信小程序后台音频管理器
      progressTimer: null,
      showAction: false,
      actionList: [
        {
          text: '分享',
          color: '#25772f'
        },
        {
          text: '收藏',
          color: '#ff4757'
        },
        {
          text: '定时关闭',
          color: '#333'
        }
      ]
    }
  },
  
  computed: {
    progressPercent() {
      if (this.duration === 0) return 0
      return (this.currentTime / this.duration) * 100
    }
  },
  
  onLoad(options) {
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight || 44
    
    // 解析传递的参数
    if (options.soundData) {
      try {
        this.soundList = JSON.parse(decodeURIComponent(options.soundData))
      } catch (e) {
        console.error('解析音乐数据失败:', e)
      }
    }
    
    if (options.currentIndex) {
      this.currentIndex = parseInt(options.currentIndex)
    }
    
    if (this.soundList.length > 0) {
      this.currentSound = this.soundList[this.currentIndex]
    }
    
    // 检查收藏状态
    this.checkFavoriteStatus()
    
    // 初始化音频
    this.initAudio()
  },
  
  onShow() {
    // 页面显示时继续播放
    // #ifdef MP-WEIXIN
    // 微信小程序后台音频会自动继续播放，无需手动处理
    if (this.backgroundAudioManager) {
      this.isPlaying = !this.backgroundAudioManager.paused
    }
    // #endif
    // #ifndef MP-WEIXIN
    if (this.audioContext && this.isPlaying) {
      this.audioContext.play()
    }
    // #endif
  },
  
  onHide() {
    // 页面隐藏时保持播放（支持后台播放）
    // #ifdef MP-WEIXIN
    // 微信小程序后台音频会自动在后台继续播放
    // #endif
    // #ifndef MP-WEIXIN
    // 其他平台音频会继续播放
    // #endif
  },
  
  onUnload() {
    // 页面销毁时清理资源
    this.clearProgressTimer()
    // #ifdef MP-WEIXIN
    if (this.backgroundAudioManager) {
      this.backgroundAudioManager.stop()
    }
    // #endif
    // #ifndef MP-WEIXIN
    if (this.audioContext) {
      this.audioContext.destroy()
    }
    // #endif
  },
  
  methods: {
    // 初始化音频
    initAudio() {
      // #ifdef MP-WEIXIN
      // 微信小程序使用后台音频管理器
      this.backgroundAudioManager = uni.getBackgroundAudioManager()
      this.setupBackgroundAudio()
      // #endif
      
      // #ifndef MP-WEIXIN
      // 其他平台使用普通音频上下文
      this.audioContext = uni.createInnerAudioContext()
      this.setupInnerAudio()
      // #endif
    },
    
    // 设置微信小程序后台音频
    setupBackgroundAudio() {
      const bgAudio = this.backgroundAudioManager
      
      // 设置音频信息
      bgAudio.title = this.currentSound.name
      bgAudio.singer = '自然之声'
      bgAudio.coverImgUrl = '/static/community_ico.png'
      bgAudio.src = this.currentSound.url
      
      // 监听音频事件
      bgAudio.onPlay(() => {
        this.isPlaying = true
        this.startProgressTimer()
      })
      
      bgAudio.onPause(() => {
        this.isPlaying = false
        this.clearProgressTimer()
      })
      
      bgAudio.onStop(() => {
        this.isPlaying = false
        this.clearProgressTimer()
        this.currentTime = 0
      })
      
      bgAudio.onTimeUpdate(() => {
        this.currentTime = bgAudio.currentTime
        this.duration = bgAudio.duration || 0
      })
      
      bgAudio.onEnded(() => {
        if (this.isLoop) {
          // 循环播放
          bgAudio.seek(0)
          bgAudio.play()
        } else {
          this.nextSound()
        }
      })
      
      bgAudio.onError((res) => {
        console.error('后台音频播放出错:', res)
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        })
      })
      
      // 开始播放
      bgAudio.play()
    },
    
    // 设置其他平台音频
    setupInnerAudio() {
      this.audioContext.src = this.currentSound.url
      this.audioContext.loop = this.isLoop
      this.audioContext.volume = this.volume / 100
      
      // 监听音频事件
      this.audioContext.onPlay(() => {
        this.isPlaying = true
        this.startProgressTimer()
      })
      
      this.audioContext.onPause(() => {
        this.isPlaying = false
        this.clearProgressTimer()
      })
      
      this.audioContext.onStop(() => {
        this.isPlaying = false
        this.clearProgressTimer()
        this.currentTime = 0
      })
      
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime
        this.duration = this.audioContext.duration || 0
      })
      
      this.audioContext.onEnded(() => {
        if (!this.isLoop) {
          this.nextSound()
        }
      })
      
      this.audioContext.onError((res) => {
        console.error('音频播放出错:', res)
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        })
      })
      
      // 开始播放
      this.audioContext.play()
    },
    
    // 开始进度计时器
    startProgressTimer() {
      this.clearProgressTimer()
      this.progressTimer = setInterval(() => {
        // #ifdef MP-WEIXIN
        if (this.backgroundAudioManager) {
          this.currentTime = this.backgroundAudioManager.currentTime || 0
          this.duration = this.backgroundAudioManager.duration || 0
        }
        // #endif
        // #ifndef MP-WEIXIN
        if (this.audioContext) {
          this.currentTime = this.audioContext.currentTime
          this.duration = this.audioContext.duration || 0
        }
        // #endif
      }, 1000)
    },
    
    // 清除进度计时器
    clearProgressTimer() {
      if (this.progressTimer) {
        clearInterval(this.progressTimer)
        this.progressTimer = null
      }
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time || isNaN(time)) return '00:00'
      const minutes = Math.floor(time / 60)
      const seconds = Math.floor(time % 60)
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    
    // 切换播放/暂停
    togglePlay() {
      // #ifdef MP-WEIXIN
      if (this.backgroundAudioManager) {
        if (this.isPlaying) {
          this.backgroundAudioManager.pause()
        } else {
          this.backgroundAudioManager.play()
        }
      }
      // #endif
      // #ifndef MP-WEIXIN
      if (this.audioContext) {
        if (this.isPlaying) {
          this.audioContext.pause()
        } else {
          this.audioContext.play()
        }
      }
      // #endif
    },
    
    // 切换循环模式
    toggleLoop() {
      this.isLoop = !this.isLoop
      // #ifndef MP-WEIXIN
      // 其他平台设置循环
      if (this.audioContext) {
        this.audioContext.loop = this.isLoop
      }
      // #endif
      // 微信小程序的循环在onEnded事件中处理
      uni.showToast({
        title: this.isLoop ? '已开启循环播放' : '已关闭循环播放',
        icon: 'none'
      })
    },
    
    // 上一首
    previousSound() {
      if (this.currentIndex > 0) {
        this.currentIndex--
      } else {
        this.currentIndex = this.soundList.length - 1
      }
      this.switchSound()
    },
    
    // 下一首
    nextSound() {
      if (this.currentIndex < this.soundList.length - 1) {
        this.currentIndex++
      } else {
        this.currentIndex = 0
      }
      this.switchSound()
    },
    
    // 切换音乐
    switchSound() {
      this.currentSound = this.soundList[this.currentIndex]
      this.checkFavoriteStatus()
      
      // #ifdef MP-WEIXIN
      if (this.backgroundAudioManager) {
        this.backgroundAudioManager.title = this.currentSound.name
        this.backgroundAudioManager.src = this.currentSound.url
        this.backgroundAudioManager.play()
      }
      // #endif
      // #ifndef MP-WEIXIN
      if (this.audioContext) {
        this.audioContext.src = this.currentSound.url
        this.audioContext.play()
      }
      // #endif
    },
    
    // 拖拽进度条
    seekTo(e) {
      // #ifdef MP-WEIXIN
      if (this.backgroundAudioManager && this.duration > 0) {
        const seekTime = (e.detail.value / 100) * this.duration
        this.backgroundAudioManager.seek(seekTime)
        this.currentTime = seekTime
      }
      // #endif
      // #ifndef MP-WEIXIN
      if (this.audioContext && this.duration > 0) {
        const seekTime = (e.detail.value / 100) * this.duration
        this.audioContext.seek(seekTime)
        this.currentTime = seekTime
      }
      // #endif
    },
    
    // 改变音量
    changeVolume(e) {
      this.volume = e.detail.value
      // #ifndef MP-WEIXIN
      // 其他平台支持音量控制
      if (this.audioContext) {
        this.audioContext.volume = this.volume / 100
      }
      // #endif
    },
    
    // 切换收藏状态
    toggleFavorite() {
      this.isFavorite = !this.isFavorite
      
      // 保存到本地存储
      const favorites = uni.getStorageSync('favoriteNatureSounds') || []
      if (this.isFavorite) {
        if (!favorites.includes(this.currentSound.name)) {
          favorites.push(this.currentSound.name)
        }
        uni.showToast({
          title: '已添加到收藏',
          icon: 'success'
        })
      } else {
        const index = favorites.indexOf(this.currentSound.name)
        if (index > -1) {
          favorites.splice(index, 1)
        }
        uni.showToast({
          title: '已取消收藏',
          icon: 'none'
        })
      }
      
      uni.setStorageSync('favoriteNatureSounds', favorites)
    },
    
    // 检查收藏状态
    checkFavoriteStatus() {
      const favorites = uni.getStorageSync('favoriteNatureSounds') || []
      this.isFavorite = favorites.includes(this.currentSound.name)
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 显示操作菜单
    showActionSheet() {
      this.showAction = true
    },
    
    // 处理操作菜单点击
    handleAction(item) {
      switch (item.text) {
        case '分享':
          this.shareMusic()
          break
        case '收藏':
          this.toggleFavorite()
          break
        case '定时关闭':
          this.showTimerDialog()
          break
      }
    },
    
    // 分享音乐
    shareMusic() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: '',
        title: `分享自然之声：${this.currentSound.name}`,
        summary: this.currentSound.description,
        imageUrl: '/static/community_ico.png',
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        },
        fail: () => {
          // 降级处理
          uni.setClipboardData({
            data: `我在听${this.currentSound.name}，${this.currentSound.description}`,
            success: () => {
              uni.showToast({
                title: '已复制到剪贴板',
                icon: 'success'
              })
            }
          })
        }
      })
    },
    
    // 定时关闭对话框
    showTimerDialog() {
      uni.showActionSheet({
        itemList: ['15分钟后关闭', '30分钟后关闭', '60分钟后关闭', '取消定时'],
        success: (res) => {
          const minutes = [15, 30, 60, 0][res.tapIndex]
          if (minutes > 0) {
            setTimeout(() => {
              if (this.audioContext) {
                this.audioContext.stop()
              }
              uni.showToast({
                title: '音乐已停止',
                icon: 'none'
              })
            }, minutes * 60 * 1000)
            
            uni.showToast({
              title: `已设置${minutes}分钟后关闭`,
              icon: 'success'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.music-player-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

// 自定义导航栏
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(20rpx);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
}

.nav-left, .nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10rpx);
}

.nav-title {
  flex: 1;
  text-align: center;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
}

// 主要内容
.main-content {
  padding-top: 200rpx;
  padding-bottom: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  position: relative;
}

// 旋转音乐标志
.music-disc-container {
  margin-bottom: 80rpx;
}

.disc-wrapper {
  width: 400rpx;
  height: 400rpx;
  position: relative;
  
  &.rotating {
    animation: rotate 20s linear infinite;
  }
}

.music-disc {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: linear-gradient(45deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0.1) 100%);
  backdrop-filter: blur(20rpx);
  border: 4rpx solid rgba(255,255,255,0.3);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 20rpx 60rpx rgba(0,0,0,0.3);
}

.disc-center {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(37, 119, 47, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
  z-index: 2;
}

.disc-ring {
  position: absolute;
  border-radius: 50%;
  border: 2rpx solid rgba(255,255,255,0.2);
  
  &.ring-1 {
    width: 200rpx;
    height: 200rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  
  &.ring-2 {
    width: 280rpx;
    height: 280rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  
  &.ring-3 {
    width: 360rpx;
    height: 360rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

// 音乐信息
.music-info {
  text-align: center;
  margin-bottom: 80rpx;
  
  .sound-name {
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 4rpx 8rpx rgba(0,0,0,0.3);
  }
  
  .sound-desc {
    font-size: 28rpx;
    color: rgba(255,255,255,0.8);
    line-height: 1.5;
  }
}

// 播放控制
.player-controls {
  width: 100%;
  padding: 0 60rpx;
}

.progress-section {
  display: flex;
  align-items: center;
  margin-bottom: 60rpx;
  
  .time-text {
    color: rgba(255,255,255,0.8);
    font-size: 24rpx;
    width: 80rpx;
    text-align: center;
  }
  
  .progress-slider {
    flex: 1;
    margin: 0 20rpx;
  }
}

.control-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;
  
  .control-btn {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: rgba(255,255,255,0.1);
    backdrop-filter: blur(10rpx);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 15rpx;
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.95);
    }
    
    &.main-play-btn {
      width: 120rpx;
      height: 120rpx;
      background: rgba(255,255,255,0.9);
      margin: 0 30rpx;
    }
    
    .control-text {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
      line-height: 1;
    }
  }
}

.volume-section {
  display: flex;
  align-items: center;
  
  .volume-slider {
    flex: 1;
    margin: 0 20rpx;
  }
  
  .volume-icon {
    color: #fff;
    font-size: 28rpx;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32rpx;
    height: 32rpx;
  }
  
  .volume-tip {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 20rpx;
    padding: 8rpx 16rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 20rpx;
    
    .volume-tip-text {
      color: rgba(255, 255, 255, 0.8);
      font-size: 22rpx;
      text-align: center;
    }
  }
}

// 左下角标签
.sound-tag {
  position: fixed;
  bottom: 60rpx;
  left: 30rpx;
  padding: 12rpx 24rpx;
  background: rgba(0,0,0,0.6);
  backdrop-filter: blur(20rpx);
  border-radius: 30rpx;
  
  .tag-text {
    color: #fff;
    font-size: 24rpx;
    font-weight: 500;
  }
}

// 动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .disc-wrapper {
    width: 320rpx;
    height: 320rpx;
  }
  
  .disc-center {
    width: 100rpx;
    height: 100rpx;
  }
  
  .disc-ring {
    &.ring-1 { width: 160rpx; height: 160rpx; }
    &.ring-2 { width: 220rpx; height: 220rpx; }
    &.ring-3 { width: 280rpx; height: 280rpx; }
  }
}
</style>